﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;

namespace PIM_ATE.Electrical
{
    class TestInstMPS
    {
        private SerialPort serialPort;

        bool _Valid;
        public bool Valid
        {
            get { return _Valid; }
            set { _Valid = value; }
        }

        bool _Enabled;
        public bool Enabled
        {
            get { return _Enabled; }
            set { _Enabled = value; }
        }


        public int OpenSerialPort(string sPortName)
        {
            if (Enabled == false)
            {
                return 0;
            }

            serialPort = new System.IO.Ports.SerialPort();
            serialPort.WriteTimeout = 1000;
            serialPort.ReadTimeout = 5000;
            serialPort.NewLine = "\r\n";

            serialPort.PortName = sPortName;
            serialPort.BaudRate = 9600;
            serialPort.DataBits = 8;
            serialPort.Parity = Parity.None;
            serialPort.StopBits = StopBits.One;
            serialPort.RtsEnable = true;
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                serialPort.Open();

            }
            catch (System.Exception e)
            {
                //MessageBox.Show(e.Message);
                return -1;
            }

            return 0;

        }

        public int Switch(string Path)
        {
            if (Enabled == false)
            {
                return 0;
            }
            serialPort.DiscardInBuffer();
            serialPort.DiscardOutBuffer();
            serialPort.WriteLine(Path);

            return 0;
        }

        public string IDN()
        {
            if (Enabled == false)
            {
                return "";
            }

            serialPort.DiscardInBuffer();
            serialPort.DiscardOutBuffer();
            serialPort.WriteLine("*IDN?");
            string retString = serialPort.ReadLine();
            return retString;

        }

        public void CloseSerialPort()
        {
            if (Enabled == false)
                return;

            Application.DoEvents();
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }

        }
    }
}
